<template>
	<view class="webview-container">
		<view v-if="loading" class="loading-container">
			<u-loading-page :loading="true" loadingText="加载中..."></u-loading-page>
		</view>
		<view v-if="error" class="error-container">
			<u-empty text="无法加载页面" mode="error"></u-empty>
			<u-button @click="retryLoad" type="primary" size="medium">重试</u-button>
		</view>
		<web-view 
			v-if="!error && webviewUrl" 
			:webview-styles="webviewStyles" 
			:src="webviewUrl"
			@error="handleError"
			@load="handleLoad"
		></web-view>
	</view>
</template>
<script>
/**
 * Copyright (c) 2013-Now http://aidex.vip All rights reserved.
 */
export default {
	data() {
		return {
			webviewUrl: '',
			originalUrl: '',
			loading: true,
			error: false,
			webviewStyles: {
				progress: {
					color: '#FF7200'
				}
			}
		};
	},
	onLoad(params) {
		this.originalUrl = params.url;
		this.webviewUrl = this.processUrl(params.url);
		
		if (params.title) {
			uni.setNavigationBarTitle({
				title: params.title
			})
		}
	},
	methods: {
		// 处理URL，添加代理或处理特殊域名
		processUrl(url) {
			if (!url) return '';
			
			// 如果是黄河水利委员会网站，使用代理
			if (url.includes('yrcc.gov.cn')) {
				// 方案1: 使用公共代理服务
				// return `https://api.allorigins.win/raw?url=${encodeURIComponent(url)}`;
				
				// 方案2: 使用自己的代理服务器
				const proxyUrl = 'http://localhost:3001/proxy';
				const targetPath = url.replace('http://www.yrcc.gov.cn', '');
				return `${proxyUrl}${targetPath}`;
				
				// 方案3: 直接访问，但处理可能的错误
				// return url;
			}
			
			return url;
		},
		
		handleError(e) {
			console.error('Webview error:', e);
			this.loading = false;
			this.error = true;
			
			// 如果是CORS或X-Frame-Options错误，提供替代方案
			if (this.originalUrl.includes('yrcc.gov.cn')) {
				uni.showModal({
					title: '访问受限',
					content: '该网站有访问限制，是否尝试在新窗口打开？',
					success: (res) => {
						if (res.confirm) {
							this.openInNewWindow();
						}
					}
				});
			}
		},
		
		handleLoad() {
			this.loading = false;
			this.error = false;
		},
		
		retryLoad() {
			this.loading = true;
			this.error = false;
			this.webviewUrl = this.processUrl(this.originalUrl);
		},
		
		openInNewWindow() {
			// #ifdef H5
			window.open(this.originalUrl, '_blank');
			// #endif
			
			// #ifdef APP-PLUS
			plus.runtime.openWeb(this.originalUrl);
			// #endif
			
			// #ifdef MP
			uni.showToast({
				title: '请复制链接到浏览器打开',
				icon: 'none'
			});
			// #endif
		}
	}
};
</script>
<style lang="scss">
.webview-container {
	width: 100%;
	height: 100vh;
	position: relative;
}

.loading-container {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 100vh;
}

.error-container {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	height: 100vh;
	padding: 40rpx;
	
	.u-button {
		margin-top: 40rpx;
	}
}
</style>
